package com.diy.sigmund.diycommon.spring;

import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.CollectionUtils;

/**
 * 包装HttpServletRequest，目的是让其输入流可重复读
 *
 * <br>对HttpServletRequest进行重写，
 * <br>1、用来接收application/json参数数据类型，即@RequestBody注解标注的参数,解决多次读取问题
 * <br>2、用来解决注解@RequestParam通过POST/PUT/DELETE/PATCH方法传递参数，解决多次读取问题
 * <br>首先看一下springboot控制器三个注解：
 * <br>1、@PathVariable注解是REST风格url获取参数的方式，只能用在GET请求类型，通过getParameter获取参数
 * <br>2、@RequestParam注解支持GET和POST/PUT/DELETE/PATCH方式，Get方式通过getParameter获取参数和post方式通过getInputStream或getReader获取参数
 * <br>3、@RequestBody注解支持POST/PUT/DELETE/PATCH，可以通过getInputStream和getReader获取参数
 * <br>原文链接：https://blog.csdn.net/yaomingyang/article/details/108246334
 *
 *
 * <br>在拦截器中调用request.getReader时会报错
 * <br>final ServletInputStream inputStream = request.getInputStream();
 * <br>// java.lang.IllegalStateException: getInputStream() has already been called for this request
 * <br>final BufferedReader reader = request.getReader();
 *
 * <br>https://blog.orchidflower.cn/2020/04/30/Using-HttpServletRequestWrapper-solve-getInputStream/
 *
 * @author ylm-sigmund
 * @since 2021/8/16 10:44
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);

        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = request.getInputStream()) {
            if (Objects.isNull(inputStream)) {
                body = stringBuilder.toString();
                return;
            }
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
            body = stringBuilder.toString();
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                throw new UnsupportedOperationException();
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }

    /**
     * 获取请求入参
     *
     * @param request HttpServletRequest
     */
    public static Map<String, Object> getParameterMap(HttpServletRequest request) {
        Map<String, Object> paramMap = new LinkedHashMap<>();
        if (request instanceof RequestWrapper) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            // 所有的Post请求不要用基本数据类型的入参，需要改为对象调用:was expecting a colon to separate field name and value
            Map<String, Object> body = JacksonUtil.toObject(requestWrapper.getBody(),
                    new TypeReference<Map<String, Object>>() {
                    });
            if (!CollectionUtils.isEmpty(body)) {
                paramMap.putAll(body);
            }
        }
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String key = names.nextElement();
            paramMap.put(key, request.getParameter(key));
        }
        return paramMap;
    }

    @Override
    public String getRemoteUser() {
        return super.getRemoteUser();
    }
}
